package com.zyz.sunliky.service.serviceImpl;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zyz.sunliky.entity.RequestData;
import com.zyz.sunliky.mapper.erp.ErpMapper;
import com.zyz.sunliky.mapper.yunshu.FinanceMapper;
import com.zyz.sunliky.mapper.yunshu.PurchaseMapper;
import com.zyz.sunliky.service.FinanceService;
import com.zyz.sunliky.util.UUIDUtils;
import org.apache.poi.hpsf.Decimal;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class FinanceServiceImpl implements FinanceService {
    public static final org.slf4j.Logger logger = LoggerFactory.getLogger(FinanceServiceImpl.class);
    @Autowired
    FinanceMapper financeMapper;
    @Autowired
    ErpMapper erpMapper;
    @Autowired
    PurchaseMapper purchaseMapper;

    @Value("${spring.yunshuurl}")
    private String URL;

    @Override
    public Map getHistorical(String id) {
        //String creater = financeMapper.getCreater(id);
        if(id.isEmpty())throw new RuntimeException("没有此员工!");
        Map<String, Decimal> amount= financeMapper.getQuantity(id);

        return amount;
    }

    @Override
    public Map getHisQuantity(RequestData data) {
        if (data == null || (data.getFkhbm() == null && data.getFkhmc() == null)) {
            throw new RuntimeException("没有此客户!");
        }
        //新客户-按名称查询 老客户-按名称加编码查询
        Map<String, Decimal> amount= financeMapper.getHisQuantity(data);
        return amount;
    }

    @Override
    public String getPriceChange(String id, String tokenid) {

        // 发送 HTTP GET 请求获取 replayToken
        String replayToken = getReplayToken(tokenid);
        if(replayToken.isEmpty())throw new RuntimeException("tokenid不能为空!");
        /**查询表头**/
        List<Map<String,Object>> headList = financeMapper.findHeadList(id);
        if(headList.isEmpty())throw new RuntimeException("没有此单据!");

        /**查询明细**/
        List<Map<String,Object>> list_mx=financeMapper.findBodyList(id);
        /**查询用户名称**/
        // String username=purchaseMapper.findUserName(id);
        // if(StringUtils.isEmpty(username))throw new RuntimeException("用户不存在");
       // String replayToken = id;
        JSONObject object = new JSONObject();
        object.put("replayToken", replayToken);
        object.put("sheetCode", "model_qtqkxcwxxdwnwfb");
        // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowInstanceId", null);  // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowCode", "workflow_qtqkxcwxxdnfb");
        object.put("workItemId", null);
        String getuuid = UUIDUtils.getuuid();
        JSONObject data=new JSONObject();
        Map map = headList.get(0);
        data.put("id", getuuid);
        map.forEach((key,value)->{
            data.put(String.valueOf(key),value);
        });
        JSONArray array=new JSONArray();
//        data.put("fid","999111");
//        data.put("ShortText1696988626296","fqqddbh");


//        String timestampString = map.get("fsqrq").toString();
//        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
//        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//        try {
//            // 将字符串解析为日期对象
//            Date date = inputFormat.parse(timestampString);
//
//            // 将日期对象格式化为指定格式的字符串
//            String formattedDate = outputFormat.format(date);
//            map.put("fsqrq",formattedDate);
//            System.out.println("格式化后的日期：" + formattedDate);
//        } catch (java.text.ParseException e) {
//            e.printStackTrace();
//        }
//        data.put("fcgsqid",map.get("id"));
//        data.put("fqqddbh",map.get("fqqddbh"));
//        data.put("fqqh",map.get("fqqh"));

        for (Map<String, Object> listMx : list_mx) {
            JSONObject item=new JSONObject();
            listMx.forEach((key,value)->{
                item.put(String.valueOf(key),value);
            });

//            /**特殊组件额外处理**/
            //JSONArray array_creater = JSONArray.parseArray("[{\"id\":\""+map.get("fsqr")+"\",\"type\":3}]");
//            JSONObject item=new JSONObject();
//            item.put("fxm","张三");
//            item.put("fnl","20");
            item.remove("id");
            array.add(item);
       }
        data.put("sales_price_details",array);
        JSONObject bizObject=new JSONObject();
        bizObject.put("schemaCode","model_qtqkxcwxxdwnwfb");
        bizObject.put("sheetCode","model_qtqkxcwxxdwnwfb");
        bizObject.put("workflowInstanceId",null);
        bizObject.put("data",data);
        object.put("bizObject",bizObject);
        //object.put("replayToken",replayToken);
        System.out.println(data);
        String s = object.toJSONString();
        String postResult = HttpRequest
                .post(URL+"/api/api/runtime/form/save")
                .header("Content-Type","application/json")
                .header("Authorization", "Bearer "+ tokenid)
                .body(s)
                .execute()
                .body();
//        updateRequestNo(getuuid);
        System.out.println(s);
        System.out.println(postResult);
       // JsonObject jsonObject = JsonParser.parseString(postResult).getAsJsonObject();

        return postResult;
    }

    @Override
    public List<Map<String,Object>> getOrderNumber(String type,String id) throws ParseException {
        if (Objects.equals(type, "") || Objects.equals(id, "")) {
            throw new RuntimeException("没有此单据!");
        }

        List<Map<String, Object>> list_mx = null;

        //1出库
        if ("1".equals(type)){
            String orderStatus = erpMapper.getOrderStatus(id);
            if (Objects.equals(orderStatus, "2")) {
                throw new RuntimeException("此单据已审核!");
            }
            String lld=financeMapper.getSunOrder(id);
            if (lld != null && !lld.isEmpty()) {
                throw new RuntimeException("此单据已发起过领料申请!");
            }
            list_mx=erpMapper.getOrderNumber(id);
            for (Map<String, Object> map : list_mx) {
                if (!map.containsKey("CPXM")) {
                    map.put("CPXM", "");
                }
                if (!map.containsKey("CKLXMC")) {
                    map.put("CKLXMC", "");
                }
                if (!map.containsKey("CKMC")) {
                    map.put("CKMC", "");
                }
                if (!map.containsKey("NBXMMC")) {
                    map.put("NBXMMC", "");
                }
                if (!map.containsKey("WBXMMC")) {
                    map.put("WBXMMC", "");
                }
                SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

// 从 map 中获取日期字符串并解析成 Date 对象
                Date date = inputFormat.parse(map.get("RQ").toString());

// 将 Date 对象格式化成指定格式的日期字符串
                String outputDate = outputFormat.format(date);
                map.put("RQ", outputDate);
                System.out.println(outputDate);

            }

        }else {

            list_mx=erpMapper.getOrderNumber1(id);
        }

        return list_mx;
    }

    @Override
    public void getStatus(String id) {
        if (null == id || "" == id) {
            throw new RuntimeException("无法找到料号编码！");
        }
        System.out.println("sqdh"+id);
//        Map<String, Object>  map = financeMapper.getStatus(id);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        map.put("createTime", sdf.format(new Date()));
        erpMapper.updateStatus(id);
    }

    @Override
    public BigDecimal getCost(String id) {
        if(StringUtils.isEmpty(id)) {
            throw new RuntimeException("物料编号为空！");
        }
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal getAmount = erpMapper.getCost(id);
        if(getAmount != null) {
            amount = getAmount;
        }
        return amount;
    }
    @Override
    public Map<String, Object> getPrice(String xsxh) {
        if(StringUtils.isEmpty(xsxh)) {
            throw new RuntimeException("客户编号或销售单号为空！");
        }
        //BigDecimal amount = BigDecimal.ZERO;
        Map<String, Object> getAmount = erpMapper.getPrice(xsxh);
        System.out.println("getAmount"+getAmount);
        return getAmount;
    }

    public String getReplayToken(String tokenid) {
        String replayToken = "";
        try {
            // 发送 HTTP GET 请求并获取响应
            String response = HttpRequest.get("http://122.225.90.194:9555/api/api/runtime/form/getReplayToken")
                    .header("Accept", "application/json")
                    .header("Authorization", "Bearer " + tokenid)
                    .timeout(5000)
                    .execute()
                    .body();
            // 打印整个响应字符串
            System.out.println("Response: " + response);
            // 解析 JSON 响应
            JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();

            // 获取名为"data"的字段的值
            replayToken = jsonObject.get("data").getAsString();
            // 打印 data 字段的值
            System.out.println("replayToken: " + replayToken);
        } catch (Exception e) {
            // 捕获可能的异常
            e.printStackTrace();
        }
        return replayToken;
    }
    @Override
    public String getPayment(String id, String tokenid) {

        // 发送 HTTP GET 请求获取 replayToken
        String replayToken = getReplayToken(tokenid);
        if(replayToken.isEmpty())throw new RuntimeException("tokenid不能为空!");
        /**查询表头**/
        List<Map<String,Object>> headList = financeMapper.findPaymentHeadList(id);
        if(headList.isEmpty())throw new RuntimeException("没有此单据!");

        /**查询明细**/
        List<Map<String,Object>> list_mx=financeMapper.findPaymentBodyList(id);
        JSONObject object = new JSONObject();
        object.put("replayToken", replayToken);
        object.put("sheetCode", "payment_application");
        // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowInstanceId", null);  // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowCode", "payment_application");
        object.put("workItemId", null);
        String getuuid = UUIDUtils.getuuid();
        JSONObject data=new JSONObject();
        Map map = headList.get(0);
        data.put("id", getuuid);
        map.forEach((key,value)->{
            data.put(String.valueOf(key),value);
        });
        JSONArray array=new JSONArray();
        for (Map<String, Object> listMx : list_mx) {
            JSONObject item=new JSONObject();
            listMx.forEach((key,value)->{
                item.put(String.valueOf(key),value);
            });
            item.remove("id");
            array.add(item);
        }
        data.put("sub_payment_application",array);
        JSONObject bizObject=new JSONObject();
        bizObject.put("schemaCode","payment_application");
        bizObject.put("sheetCode","payment_application");
        bizObject.put("workflowInstanceId",null);
        bizObject.put("data",data);
        object.put("bizObject",bizObject);
        System.out.println(data);
        String s = object.toJSONString();
        String postResult = HttpRequest
                .post(URL+"/api/api/runtime/form/save")
                .header("Content-Type","application/json")
                .header("Authorization", "Bearer "+ tokenid)
                .body(s)
                .execute()
                .body();
        System.out.println(s);
        System.out.println(postResult);
        return postResult;
    }

    @Override
    public List<Map<String, Object>> getsales(String id) {

        List<Map<String, Object>> sales =  erpMapper.sales(id);
        System.out.println("id"+id);
        return sales;
    }

    @Override
    public Map<String, BigDecimal> getProductCost(String id) {
        System.out.println("id"+id);
        Map<String,BigDecimal> productCost = erpMapper.getProductCost(id);
        return productCost;
    }

}
